package com.summer.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.summer.commonException.CommonError;
import com.summer.commonException.XueChengException;
import com.summer.content.config.MultipartSupportConfig;
import com.summer.content.dao.CourseBaseMapper;
import com.summer.content.dao.CourseMarketMapper;
import com.summer.content.dao.CoursePublishMapper;
import com.summer.content.dao.CoursePublishPreMapper;
import com.summer.content.feignClient.MediaClient;
import com.summer.content.service.CourseBaseService;
import com.summer.content.service.CoursePublishService;
import com.summer.content.service.TeachPlanService;
import com.summer.dto.CourseBaseInfoDto;
import com.summer.dto.CoursePreviewDto;
import com.summer.dto.TeachPlanDto;
import com.summer.pojo.CourseBase;
import com.summer.pojo.CourseMarket;
import com.summer.pojo.CoursePublish;
import com.summer.pojo.CoursePublishPre;
import com.summer.messagesdk.model.po.MqMessage;
import com.summer.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private TeachPlanService teachPlanService;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    @Autowired
    private MqMessageService mqMessageService;

    @Autowired
    private MediaClient mediaClient;

    @Override
    public CoursePreviewDto getCoursePreview(Long courseId) {
        // 获取课程基本信息与营销信息
        CourseBaseInfoDto baseAndMarketInfo = courseBaseService.getBaseAndMarketInfo(courseId);

        // 获取课程计划信息
        List<TeachPlanDto> coursePlanList = teachPlanService.getCoursePlanById(courseId);

        // 封装
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(baseAndMarketInfo);
        coursePreviewDto.setTeachplans(coursePlanList);
        return coursePreviewDto;
    }

    @Override
    public void commitAudit(Long companyId, Long courseId) {
        //约束校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            XueChengException.cast("[课程审核] 课程不存在");
        }
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        //当前审核状态为已提交不允许再次提交
        if("202003".equals(auditStatus)){
            XueChengException.cast("当前为等待审核状态，审核完成可以再次提交。");
        }
        //本机构只允许提交本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengException.cast("不允许提交其它机构的课程。");
        }

        //课程图片是否填写
        if(StringUtils.isEmpty(courseBase.getPic())){
            XueChengException.cast("提交失败，请上传课程图片");
        }

        //添加课程预发布记录
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息加部分营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.getBaseAndMarketInfo(courseId);
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表
        coursePublishPre.setMarket(courseMarketJson);

        //查询课程计划信息
        List<TeachPlanDto> teachplanTree = teachPlanService.getCoursePlanById(courseId);
        if(teachplanTree.size()<=0){
            XueChengException.cast("提交失败，还没有添加课程计划");
        }
        //转json
        String teachplanTreeString = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanTreeString);

        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPreUpdate == null){
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        }else{
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本表的审核状态、发布状态
        courseBase.setAuditStatus("202003");
        courseBase.setStatus("203001");
        int update = courseBaseMapper.updateById(courseBase);
        if (update <= 0){
            XueChengException.cast("【课程审核】 课程基本信息更新审核状态失败");
        }
    }

    // 课程预览
    @Transactional
    @Override
    public void coursePublish(Long companyId, Long courseId) {
        // 0. 数据准备
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (courseBase == null){
            XueChengException.cast("【课程发布接口】： 此课程id信息不存在");
        }
        if (coursePublishPre == null){
            XueChengException.cast("【课程发布接口】： 请先提交审核");
        }

        // 1. 逻辑校验：本机构才能发布、审核通过才能发布、重复提交判断
        if (!Objects.equals(companyId, courseBase.getCompanyId())){
            XueChengException.cast("【课程发布接口】：非本机构不能发布课程");
        }
        if (!courseBase.getAuditStatus().equals("202004")){
            XueChengException.cast("【课程发布接口】：请先通过审核再发布");
        }
        if (courseBase.getStatus().equals("203002")){
            XueChengException.cast("【课程发布接口】：请勿重复提交");
        }
        if (coursePublishPre.getStatus().equals("203002")){
            XueChengException.cast("【课程发布接口】：请勿重复提交");
        }

        // 2. 更改预发布表与基本表的状态字段（封装与调接口）
        courseBase.setStatus("203002");
        int updateCourseBase = courseBaseMapper.updateById(courseBase);
        if (updateCourseBase <= 0){
            XueChengException.cast("【课程发布接口】：基本表更新发布状态失败");
        }
        coursePublishPre.setStatus("203002");
        int updateCoursePublishPre = coursePublishPreMapper.updateById(coursePublishPre);
        if (updateCoursePublishPre <= 0){
            XueChengException.cast("【课程发布接口】：预发布表更新发布状态失败");
        }

        // 3. 将预发布表信息同步到发布表
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        if (coursePublishMapper.selectById(courseId) == null){  // 解决修改后再次提交
            int insertCoursePublish = coursePublishMapper.insert(coursePublish);
            if (insertCoursePublish <= 0){
                XueChengException.cast("【课程发布接口】：发布表同步信息（插入）失败");
            }
        }else {
            int update = coursePublishMapper.updateById(coursePublish);
            if (update <= 0){
                XueChengException.cast("【课程发布接口】：发布表同步信息（更新）失败" );
            }
        }

        // 4. 将发布任务添加到消息队列表 （封装与调接口）
        log.info("正在将任务添加到消息队列表......");
        MqMessage mqMessage = mqMessageService.addMessage("course_publish",
               String.valueOf(courseId),
                null,
                null);
        if (mqMessage == null){
            XueChengException.cast(CommonError.UNKOWN_ERROR);
        }

        // 5. 删除预发布表
        int i = coursePublishPreMapper.deleteById(courseId);
        if (i <= 0) {
            XueChengException.cast("【课程发布接口】：删除预发布表失败");
        }
    }


    // 返回html页面文件，此方法若出现异常返回null
    public File generateHtmlToFile(long courseId) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try{
            //配置freemarker(包名包括freemarker)
            Configuration configuration = new Configuration(Configuration.getVersion());

            String classpath = this.getClass().getResource("/").getPath(); //得到classpath路径
            //指定模板路径,classpath下templates下
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //准备模板文件
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据模型
            CoursePreviewDto coursePreviewInfo = this.getCoursePreview(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //参数1：模板，参数2：数据模型, content: 页面源代码
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            // 将字符串转换为输入流
            File coursePage = File.createTempFile("coursePage", ".html");
            coursePage.deleteOnExit();
            inputStream = IOUtils.toInputStream(content);
            outputStream = new FileOutputStream(coursePage);
            IOUtils.copy(inputStream, outputStream); //org.apache.commons.io.IOUtils

            // 创建输出流，将输入流拷贝到输出流
            log.info("临时文件路径：{}", coursePage.getAbsolutePath());
            return coursePage;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    // 将html上传到minio, 这里不处理异常，让异常向上抛出
    public void insert2minio(File htmlFile, String objectName){
        //通过feign远程调用media-api中的方法
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(htmlFile);
        String result = mediaClient.uploadFile(multipartFile, objectName);
        if (result == null) {
            log.error("触发降级保护");
            XueChengException.cast("页面上传到minio失败");
        }
    }

    // 根据id获取课程发布信息
    @Override
    public CoursePublish getById(long courseId) {

        return coursePublishMapper.selectOne(
                new LambdaQueryWrapper<CoursePublish>().eq(CoursePublish::getId, courseId));


    }

}
